﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PracticeSimple.Models;
using System.Web.Security;

using DataLayer;
using BusinessObjects;


namespace PracticeSimple.Controllers
{
    public class HomeController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            LoginModel model = new LoginModel();
            model.Username = "chuck.pfaff";
            model.Password = "pfatcat";
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            var userName = model.Username;
            var password = model.Password;

            DataLayer.UserRepository userRepo = new DataLayer.UserRepository();
            BusinessObjects.User user = userRepo.FindUser(userName);

            if (user == null ||password != user.Password)
            {
                model.failedLogin = true; 
            }
            else
            {
                var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
                                               DateTime.Now.AddSeconds(120), true, "");

                string cookieContents = FormsAuthentication.Encrypt(authTicket);

                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                {
                    Expires = authTicket.Expiration,
                    Path = FormsAuthentication.FormsCookiePath
                };

                if (Response != null)
                {
                    Response.Cookies.Add(cookie);
                }

                Session["FacilityID"] = user.FacilityID;
                Session["UserID"] = user.UserID;

                Response.Redirect("Dashboard");
            }

            return View(model);
        }
    }
}
